Grab_Callback.py

Get Image(s) via Callback

It shows how to get images via callback. The major steps include creating a handle, turning on the camera, registering a callback, starting grabbing images, getting image information via callback, stopping grabbing images, turning off the camera, and destroying the handle.

1 # -- coding: utf-8 --
2 
3 import sys
4 import copy
5 import platform
6 import os
7 from ctypes import *
8 
9 
10 # Compatible with different operating systems to load DDL
11 currentsystem = platform.system()
12 if currentsystem == 'Windows':
13  sys.path.append(os.path.join(os.getenv('MVCAM_COMMON_RUNENV'), "Samples", "Python", "MvImport"))
14 else:
15  sys.path.append(os.path.join("..", "..", "MvImport"))
16 
17 from MvCameraControl_class import *
18 
19 
20 # Compatible with input processing of Python 2.X and 3.X
21 if sys.version_info[0] < 3:
22  # Python 2.x
23  input_func = raw_input
24 else:
25  # Python 3.x
26  input_func = input
27 
28 # Decoding Characters
29 def decoding_char(ctypes_char_array):
30  """
31  Safely decode a string from a ctypes character array.
32  Compatible with Python 2.x and 3.x, as well as 32-bit and 64-bit environments.
33  """
34  byte_str = memoryview(ctypes_char_array).tobytes()
35 
36  # Truncate at the first null character
37  null_index = byte_str.find(b'\x00')
38  if null_index != -1:
39  byte_str = byte_str[:null_index]
40 
41  # Attempt to decode using multiple encodings
42  for encoding in ['gbk', 'utf-8', 'latin-1']:
43  try:
44  return byte_str.decode(encoding)
45  except UnicodeDecodeError:
46  continue
47 
48  # If all encodings fail, use a replacement strategy
49  return byte_str.decode('latin-1', errors='replace')
50 
51 
52 fun_ctype = get_platform_functype()
53 FrameInfoCallBack2 = fun_ctype(None, POINTER(MV_FRAME_OUT), c_void_p, c_bool)
54 def image_callback2(pstFrame, pUser, bAutoFree):
55  stFrame = cast(pstFrame, POINTER(MV_FRAME_OUT)).contents
56  if stFrame:
57  print ("get one frame: Width[%d], Height[%d], nFrameNum[%d]" % (stFrame.stFrameInfo.nWidth, stFrame.stFrameInfo.nHeight, stFrame.stFrameInfo.nFrameNum))
58 
59  #Non automatic release mode. Releasing resources manually is required.
60  if bAutoFree == False :
61  if pUser != None:
62  User = ctypes.cast(pUser, ctypes.py_object).value
63  User.MV_CC_FreeImageBuffer(stFrame)
64  else :
65  print ("user is null, invalid")
66 
67 CALL_BACK_FUN2 = FrameInfoCallBack2(image_callback2)
68 
69 
70 
71 if __name__ == "__main__":
72  try:
73  # Initialize SDK resources
74  MvCamera.MV_CC_Initialize()
75 
76  SDKVersion = MvCamera.MV_CC_GetSDKVersion()
77  print ("SDKVersion[0x%x]" % SDKVersion)
78 
79  deviceList = MV_CC_DEVICE_INFO_LIST()
80  tlayerType = (MV_GIGE_DEVICE | MV_USB_DEVICE | MV_GENTL_CAMERALINK_DEVICE
81  | MV_GENTL_CXP_DEVICE | MV_GENTL_XOF_DEVICE)
82 
83  # Enumerate devices
84  ret = MvCamera.MV_CC_EnumDevices(tlayerType, deviceList)
85  if ret != 0:
86  print ("enum devices fail! ret[0x%x]" % ret)
87  sys.exit()
88 
89  if deviceList.nDeviceNum == 0:
90  print ("find no device!")
91  sys.exit()
92 
93  print ("find %d devices!" % deviceList.nDeviceNum)
94 
95  for i in range(0, deviceList.nDeviceNum):
96  mvcc_dev_info = cast(deviceList.pDeviceInfo[i], POINTER(MV_CC_DEVICE_INFO)).contents
97  if mvcc_dev_info.nTLayerType == MV_GIGE_DEVICE or mvcc_dev_info.nTLayerType == MV_GENTL_GIGE_DEVICE:
98  print ("\ngige device: [%d]" % i)
99  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stGigEInfo.chModelName)
100  print ("device model name: %s" % strModeName)
101  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stGigEInfo.chSerialNumber)
102  print("device serial number: %s" % strSerialNumber)
103  nip1 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0xff000000) >> 24)
104  nip2 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x00ff0000) >> 16)
105  nip3 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x0000ff00) >> 8)
106  nip4 = (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x000000ff)
107  print ("current ip: %d.%d.%d.%d\n" % (nip1, nip2, nip3, nip4))
108  elif mvcc_dev_info.nTLayerType == MV_USB_DEVICE:
109  print ("\nu3v device: [%d]" % i)
110  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stUsb3VInfo.chModelName)
111  print ("device model name: %s" % strModeName)
112 
113  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stUsb3VInfo.chSerialNumber)
114  print ("device serial number: %s" % strSerialNumber)
115  elif mvcc_dev_info.nTLayerType == MV_GENTL_CAMERALINK_DEVICE:
116  print ("\nCML device: [%d]" % i)
117  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stCMLInfo.chModelName)
118  print ("device model name: %s" % strModeName)
119 
120  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stCMLInfo.chSerialNumber)
121  print ("device serial number: %s" % strSerialNumber)
122  elif mvcc_dev_info.nTLayerType == MV_GENTL_CXP_DEVICE:
123  print ("\nCXP device: [%d]" % i)
124  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stCXPInfo.chModelName)
125  print ("device model name: %s" % strModeName)
126 
127  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stCXPInfo.chSerialNumber)
128  print ("device serial number: %s" % strSerialNumber)
129  elif mvcc_dev_info.nTLayerType == MV_GENTL_XOF_DEVICE:
130  print ("\nXoF device: [%d]" % i)
131  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stXoFInfo.chModelName)
132  print ("device model name: %s" % strModeName)
133 
134  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stXoFInfo.chSerialNumber)
135  print ("device serial number: %s" % strSerialNumber)
136 
137  nConnectionNum = input_func("please input the number of the device to connect:")
138 
139  if int(nConnectionNum) >= deviceList.nDeviceNum:
140  print ("intput error!")
141  sys.exit()
142 
143  # Create the camera instance
144  cam = MvCamera()
145 
146  # Select a device, and create a handle
147  stDeviceList = cast(deviceList.pDeviceInfo[int(nConnectionNum)], POINTER(MV_CC_DEVICE_INFO)).contents
148 
149  ret = cam.MV_CC_CreateHandle(stDeviceList)
150  if ret != 0:
151  raise Exception ("create handle fail! ret[0x%x]" % ret)
152 
153  # Turn on the device
154  ret = cam.MV_CC_OpenDevice(MV_ACCESS_Exclusive, 0)
155  if ret != 0:
156  raise Exception ("open device fail! ret[0x%x]" % ret)
157 
158  # Get optimal packet size (only supported by GigE devices)
159  if stDeviceList.nTLayerType == MV_GIGE_DEVICE or stDeviceList.nTLayerType == MV_GENTL_GIGE_DEVICE:
160  nPacketSize = cam.MV_CC_GetOptimalPacketSize()
161  if int(nPacketSize) > 0:
162  ret = cam.MV_CC_SetIntValue("GevSCPSPacketSize",nPacketSize)
163  if ret != 0:
164  print ("Warning: Set Packet Size fail! ret[0x%x]" % ret)
165  else:
166  print ("Warning: Get Packet Size fail! ret[0x%x]" % nPacketSize)
167 
168  # Set trigger mode to off
169  ret = cam.MV_CC_SetEnumValue("TriggerMode", MV_TRIGGER_MODE_OFF)
170  if ret != 0:
171  raise Exception ("set trigger mode fail! ret[0x%x]" % ret)
172 
173  #Register an image grabbing callback
174  ret = cam.MV_CC_RegisterImageCallBackEx2(CALL_BACK_FUN2, ctypes.py_object(cam), True)
175  if ret != 0:
176  raise Exception ("register image callback fail! ret[0x%x]" % ret)
177 
178  # Start grabbing images
179  ret = cam.MV_CC_StartGrabbing()
180  if ret != 0:
181  raise Exception ("start grabbing fail! ret[0x%x]" % ret)
182 
183  print ("press Enter key to stop grabbing.")
184  input_func()
185 
186  # Stop grabbing images
187  ret = cam.MV_CC_StopGrabbing()
188  if ret != 0:
189  raise Exception ("stop grabbing fail! ret[0x%x]" % ret)
190 
191  # Turn off the device
192  ret = cam.MV_CC_CloseDevice()
193  if ret != 0:
194  raise Exception ("close deivce fail! ret[0x%x]" % ret)
195 
196  # Destroy the handle
197  cam.MV_CC_DestroyHandle()
198 
199  except Exception as e:
200  print(e)
201  cam.MV_CC_CloseDevice()
202  cam.MV_CC_DestroyHandle()
203  finally:
204  # Release SDK resources
205  MvCamera.MV_CC_Finalize()